package Classification

import (
	session2 "OnlineRetailers/controllers/admin/session"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models/Admin"
	error2 "OnlineRetailers/models/errorDeal"
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"os"
)

type UpdateClassification struct {
	beego.Controller
}

func (c *UpdateClassification) UpdateClassification() {

	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()

	var addr = "/Classification/UpdateClassification"
	var err error

	productDetailed := []*Admin.ProductDetailed{}
	classification := &Admin.Classification{}
	log := &error2.Log{}
	mes := &error2.Mes{}

	o := orm.NewOrm()

	imgChange := c.GetString("imgChange")

	err = json.Unmarshal([]byte(c.GetString("classification")), classification)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	err = json.Unmarshal([]byte(c.GetString("product")), &productDetailed)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	err = session2.CheckSession(c.Ctx.Request.Header["Session"], 1)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	err = DeleteProductM2M(o, classification.ClassificationId)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	classification.ProductDetailed = productDetailed
	//fmt.Println(class)
	if len(classification.ProductDetailed) != 0 {
		err = PostProductM2M(o, classification)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "402", err, addr, err.Error())
			return
		}
	}

	if imgChange != "" {
		err = os.Remove("." + classification.PrimariesImage)
		classification.PrimariesImage = imgChange
	}

	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
	}
	//fmt.Println(key)

	_, err = o.Update(classification)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	mes.Mes = "success"
	mes.Code = "200"
	c.Data["json"] = mes
}
